using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class ExceptionCatcher : MonoBehaviour
{
    [SerializeField]
    private Text lastErrorInfo;
    [SerializeField]
    private Text allErrorInfo;
    [SerializeField]
    private Button showAllBtn;

    private StringBuilder stringBuilder = new StringBuilder();
    void Start()
    {
        Application.logMessageReceived += OnLogCallback;
        showAllBtn.onClick.AddListener(() => 
        {
            if(!allErrorInfo.enabled)
            {
                allErrorInfo.enabled = true;
                ShowAllError();
                return;
            }
            allErrorInfo.enabled = false;
        });
    }

    private void OnDestroy()
    {
        Application.logMessageReceived -= OnLogCallback;
    }

    private void OnLogCallback(string condition, string stackTrace, LogType type)
    {
        if (type == LogType.Error || type == LogType.Exception)
        {
            condition += "\n";
            stringBuilder.Append(condition);
            
            lastErrorInfo.text = condition;
        }
    }

    private void ShowAllError()
    {
        allErrorInfo.text = stringBuilder.ToString();
    }
}
